package com.mytx.common.utils;

import com.mytx.common.constant.Constant;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtTokenUtils {
    private static final String CLAIM_KEY_USERNAME = "sub";
    private static final String CLAIM_KEY_ID = "id";
    private static final String CLAIM_KEY_CREATED = "created";
    private static final String CLAIM_KEY_ROLES = "roles";

    // @Value("${jwt.token.secret}")
    private String secret;

    // @Value("${jwt.token.expiration}")
    private int expiration; //过期时长，单位为秒,可以通过配置写入。

    public String getUsernameFromToken(String token,String secret) {
        String username;
        try {
            username = getClaimsFromToken(token,secret).getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    public Date getCreatedDateFromToken(String token,String secret) {
        Date created;
        try {
            final Claims claims = getClaimsFromToken(token,secret);
            created = new Date((Long) claims.get(CLAIM_KEY_CREATED));
        } catch (Exception e) {
            created = null;
        }
        return created;
    }

    public Date getExpirationDateFromToken(String token,String secret) {
        Date expiration;
        try {
            final Claims claims = getClaimsFromToken(token,secret);
            expiration = claims.getExpiration();
        } catch (Exception e) {
            expiration = null;
        }
        return expiration;
    }

    public static Claims getClaimsFromToken(String token,String secret) {
        Claims claims;
        try {
            claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }

    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }

    private Boolean isTokenExpired(String token,String secret) {
        final Date expiration = getExpirationDateFromToken(token,secret);
        return expiration.before(new Date());
    }


    public String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    public Boolean canTokenBeRefreshed(String token,String secret) {
        return !isTokenExpired(token,secret);
    }

    public String refreshToken(String token,String secret) {
        String refreshedToken;
        try {
            final Claims claims = getClaimsFromToken(token,secret);
            claims.put(CLAIM_KEY_CREATED, new Date());
            refreshedToken = generateToken(claims);
        } catch (Exception e) {
            refreshedToken = null;
        }
        return refreshedToken;
    }

    public static Boolean validateToken(String token,String secret) {

        Claims claims = getClaimsFromToken(token,secret);

        final Date created = claims.getExpiration();
        return  created.after(new Date());
    }


    public static String genToken(Object salt,String uId){
        Map<String, Object> claims = new HashMap<>();
        claims.put("salt", salt);
        claims.put("u_id", uId);
        Date expireDate = DateUtils.addDay(new Date(), Constant.LOGIN_EXPIRE_TIME);
        //生成token
        String token = Jwts.builder()
                .setClaims(claims)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, "#$%$TFDGTRYU%^&#$%TERYHFRTY")
                .compact();
        return token;
    }
}
